import { deleteAddress, getAllAddress ,defaultAddress } from "../../server/address"

// pages/address/address.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:null,
    type:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  toAddAddress(){
    wx.navigateTo({
      url: '/pages/add_address/add_address',
    })
  },
  onShow(){
    getAllAddress().then(res => {
      // console.log(res.data);
      this.setData({
        address:res.data
      })
    })
  },
  toDeleteAddress(e){
    // console.log(e.target.dataset.id);
    deleteAddress(e.target.dataset.id).then( () => {
      let address = this.data.address.filter(item => item.id != e.target.dataset.id)
      // console.log(address);
      this.setData({
        address
      })
    })
  },
  editAdress(e){
    wx.navigateTo({
      url: "/pages/add_address/add_address?id=" + e.target.dataset.id,
    })
  },
  backPreview(e){
    // console.log(e.target.dataset.id);
    console.log(getCurrentPages()[getCurrentPages().length-1].route);
    if(getCurrentPages()[getCurrentPages().length-2].route == "pages/preview/preview"){
      if(getCurrentPages())
      wx.setStorageSync('addressId', e.target.dataset.id)
      wx.navigateBack({
        delta: 1
      })
    }
    },
    getDefaultAddress(e){
      //把地址设置为默认地址

      // console.log(e.target.dataset.id);
      defaultAddress(e.target.dataset.id).then( () => {
        this.setData({
          address:this.data.address.filter(item => {
            if(item.id == e.target.dataset.id){
              item.is_default = 1
            }else{
              item.is_default = 0
            }
            return item
          })
        })
      })
    }
})
